<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <AreaTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form size="large" class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true"
          label-width="68px">
          <el-form-item label="IP地址" prop="hostName">
            <el-input @input="handleQuery" v-model="queryParams.hostName" placeholder="请输入IP地址" clearable
              @keyup.enter="handleQuery" class="!w-240px" />
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input @input="handleQuery" v-model="queryParams.name" placeholder="请输入名称" clearable
              @keyup.enter="handleQuery" class="!w-240px" />
          </el-form-item>

          <el-form-item label="状态" prop="status">
            <el-select clearable @change="handleQuery" class="!w-240px" v-model="queryParams.status" placeholder="请选择"
              style="width: 100%">
              <el-option v-for="dict in getIntDictOptionsString(DICT_TYPE.DEVICE_STATUS)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="设备类型" prop="deviceType">
            <el-tree-select @change="handleQuery" clearable v-model="queryParams.deviceType" :data="typeList"
              :props="defaultPropsType" check-strictly node-key="id" placeholder="请选择设备类型"
              class="!w-240px !important" />
          </el-form-item>

          <el-form-item>
            <el-button @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" /> 搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" /> 重置
            </el-button>
            <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['nms:company-property:create']">
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button type="success" plain @click="handleExport" :loading="exportLoading"
              v-hasPermi="['nms:company-property:export']">
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
            <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
              v-hasPermi="['nms:company-property:delete']">
              <Icon icon="ep:delete" class="mr-5px" /> 批量删除
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table :header-cell-style="{ background: '#e6f7ef', color: '#008c46' }" row-key="id" border
          v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="IP地址" align="center" prop="hostName" width="150" />
          <el-table-column label="名称" align="center" prop="name" width="150">
            <template #default="{ row }">
              <el-button type="success" text style="font-size: 14px" @click="visitDetail(row.id)">
                {{ row.name }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.DEVICE_STATUS" :value="scope.row.devices.status" />
            </template>
          </el-table-column>
          <el-table-column label="设备类型" align="center" prop="deviceTypeName" width="150" />
          <el-table-column label="业务类型" align="center" prop="businessType" width="150" />
          <el-table-column label="区域" align="center" prop="areaName" width="150" />

          <el-table-column label="CPU使用率" align="center" prop="cpuUsage" width="120">
            <template #default="scope">
              <div class="demo-progress">
                <el-progress :percentage="scope.row.cpuUsage" />
              </div>
            </template>
          </el-table-column>

          <el-table-column label="内存使用率" align="center" prop="memUsage" width="120">
            <template #default="scope">
              <div class="demo-progress">
                <el-progress :percentage="scope.row.memUsage" />
              </div>
            </template>
          </el-table-column>


          <el-table-column label="厂商" align="center" prop="manufacturer" width="120" />
          <el-table-column label="型号" align="center" prop="model" width="120" />
          <el-table-column label="序列号" align="center" prop="serial" width="120" />
          <el-table-column label="生产日期" align="center" prop="manufactureDate" width="120" />
          <el-table-column label="质保到期日期" align="center" prop="warrantyDate" width="120" />
          <el-table-column label="设备分布位置" align="center" prop="location" width="120" />
          <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
          <el-table-column label="操作" fixed="right" align="center" min-width="220px">
            <template #default="scope">
              <!-- <el-button type="primary" plain @click="viewDetails(scope.row.id)">
                <Icon icon="ep:view" /> 详情
              </el-button> -->
              <el-button type="primary" plain @click="openForm('update', scope.row.id)"
                v-hasPermi="['nms:company-property:update']">
                <Icon icon="ep:edit" /> 编辑

              </el-button>
              <el-button type="danger" plain @click="handleDelete(scope.row.id)"
                v-hasPermi="['nms:company-property:delete']">
                <Icon icon="ep:delete" /> 删除
              </el-button>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </ContentWrap>
    </el-col>
  </el-row>
  <!-- 表单弹窗：添加/修改 -->
  <CompanypropertyForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { CompanypropertyApi, Companyproperty } from '@/api/business/companyproperty'
import CompanypropertyForm from './CompanyPropertyForm.vue'
import AreaTree from './AreaTree.vue'
import { getIntDictOptions, getIntDictOptionsString, DICT_TYPE } from '@/utils/dict'
import { CompanyDeviceTypeApi, CompanyDeviceType } from '@/api/business/localCompanyDevicetType'
import { defaultProps, handleTree } from '@/utils/tree'
const route = useRoute() // 路由
const router = useRouter() // 路由
import { useRoute, useRouter } from 'vue-router'

/** 资产 列表 */
defineOptions({ name: 'Companyproperty' })

const viewRef = ref()

const openViewDialog = (id) => {
  viewRef.value.openDetailInfo(id)
}

const visitDetail = (id) => {
  router.push({
    name: 'deviceDetailView',
    query: {
      id: id
    }
  })
}


const defaultPropsType = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf', // 用于识别叶子节点
  emitPath: false,
  disabled: (data, node) => {
    // 方法 1：根据 children 判断（有 children 就是父节点）
    // return !!(node.children && node.children.length > 0)

    // 方法 2：根据 leaf 字段判断（更推荐，如果你的数据有 leaf 标志）
    // return !data.leaf
    return data.parentId == 0
  }
}

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Companyproperty[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  hostName: undefined,
  name: undefined,
  deviceType: undefined,
  area: undefined,
  status: undefined,
  snmpDisable: undefined,
  disabled: undefined

})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 处理区域被点击 */
const handleDeptNodeClick = async (row: any) => {
  if (row === undefined) {
    queryParams.area = undefined
    await getList()
  } else {
    queryParams.area = row.id
    await getList()
  }
}

const typeList = ref<Tree[]>([]) // 树形结构

/** 获得树 */
const getTypeTree = async () => {
  const res = await CompanyDeviceTypeApi.getCompanyDeviceTypeList(null)
  typeList.value = []
  typeList.value.push(...handleTree(res))
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CompanypropertyApi.getCompanypropertyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

//查看详情
const openView = ref(false)

const detailData = ref()
const viewDetails = async (id) => {
  detailData.value = await CompanypropertyApi.getCompanyproperty(id)
  openView.value = true
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CompanypropertyApi.deleteCompanyproperty(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除资产 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await CompanypropertyApi.deleteCompanypropertyList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Companyproperty[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CompanypropertyApi.exportCompanyproperty(queryParams)
    download.excel(data, '资产.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getTypeTree()
})
</script>


<style scoped>
.demo-progress .el-progress--line {
  margin-bottom: 15px;
  max-width: 600px;
}
</style>
